package com.loong.system.handler;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loong.common.domain.BaseQuery;
import com.loong.common.domain.Pager;
import com.loong.common.enumerate.ConfigType;
import com.loong.common.executor.AsyncExecutor;
import com.loong.common.redis.RedisTools;
import com.loong.common.utils.TransformUtils;
import com.loong.data.service.IGoodsService;
import com.loong.data.service.IShopService;
import com.loong.global.constant.RedisKey;
import com.loong.system.business.SystemConfigureBusiness;
import com.loong.system.common.backend.param.SystemConfigureParam;
import com.loong.system.common.backend.param.SystemConfigureQueryParam;
import com.loong.system.common.backend.result.SystemConfigureResult;
import com.loong.system.common.forehead.param.SystemConfigureForeheadQueryParam;
import com.loong.system.common.forehead.result.SystemConfigureForeheadResult;
import com.loong.system.common.forehead.result.SystemConfigureRedisForeheadResult;
import com.loong.system.model.SystemConfigure;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SystemConfigureHandler {
    @Resource
    private SystemConfigureBusiness systemConfigureBusiness;
    @Resource
    private AsyncExecutor asyncExecutor;
    @DubboReference
    private IShopService iShopHandler;
    @DubboReference
    private IGoodsService iGoodsHandler;



    /**
     * 保存配置信息
     * @param param
     */
    public void save(SystemConfigureParam param){
        SystemConfigure configure = TransformUtils.transform(param, SystemConfigure.class);
        systemConfigureBusiness.save(configure);
        asyncExecutor.async(()-> initByPositionCode(param.getPositionCode()));
    }


    /**
     * 更新配置
     * @param param
     */
    public void update(SystemConfigureParam param){
        systemConfigureBusiness.updateByPrimaryKeySelective(TransformUtils.transform(param, SystemConfigure.class));
        SystemConfigure dbModel = systemConfigureBusiness.findById(param.getId());
        //是null就代表是禁用启用的请求
        if(Objects.isNull(param.getPositionCode())){
            asyncExecutor.async(()-> initByPositionCode(dbModel.getPositionCode()));
            return;
        }
        log.debug("开始进入异步更新redis====={}"+dbModel);
        if(dbModel.getPositionCode().equals(param.getPositionCode())){
            asyncExecutor.async(()-> initByPositionCode(param.getPositionCode()));
        }else{
            asyncExecutor.async(()-> initByPositionCode(param.getPositionCode()));
            asyncExecutor.async(()-> initByPositionCode(dbModel.getPositionCode()));
        }

    }


    /**
     *根据id删除配置
     * @param id 配置类型的id
     */
    public void deleteConfigureById(Long id){
        SystemConfigure dbModel = systemConfigureBusiness.findById(id);
        systemConfigureBusiness.deleteById(id);
        asyncExecutor.async(()-> initByPositionCode(dbModel.getPositionCode()));
    }

    /**
     * 分页查询
     * @param baseQuery
     * @param param
     * @return
     */
    public Pager<SystemConfigureResult> pageQuery(BaseQuery baseQuery, SystemConfigureQueryParam param){
        Pager<SystemConfigure> manageApisPager = systemConfigureBusiness.pageQuery(baseQuery, () -> systemConfigureBusiness.query(param));
        return TransformUtils.transformPage(manageApisPager, SystemConfigureResult.class);
    }


    /**
     * 根据位置id获取配置（这里是轮播图）
     * @param param
     * @return
     */
    public List<SystemConfigureForeheadResult> getConfigure(SystemConfigureForeheadQueryParam param){
        return TransformUtils.transformList(systemConfigureBusiness.query(TransformUtils.transform(param, SystemConfigureQueryParam.class)), SystemConfigureForeheadResult.class);
    }

    /**
     * 根据位置id刷新
     */
    public void initByPositionCode(String code ){
        log.debug("=======根据位置code刷新redis 配置信息开始=======");
        // 查询指定位置 code下的配置
        Date now = new Date();
        List<SystemConfigure> all = systemConfigureBusiness.query(SystemConfigureQueryParam.builder()
                .positionCode(code)
                .startTime(now)
                .endTime(now)
                .configStatus(true)
                .build());
        if(CollectionUtils.isEmpty(all)){
            RedisTools.template().delete(RedisKey.SYSTEM.CONFIGURE_POSITION_CODE+code);
            //RedisTools.valueOperations().set(RedisKey.SYSTEM.CONFIGURE_POSITION_CODE +code,null);
            log.debug("=======根据位置code刷新redis 配置信息成功=======");
            return;
        }
        List<SystemConfigureForeheadResult> systemConfigureForeheadResults = TransformUtils.transformList(all, SystemConfigureForeheadResult.class);
        // 初始化配置内容
        List<SystemConfigureForeheadResult> collect = systemConfigureForeheadResults.stream()
                .map(this::apply)
                .sorted(Comparator.comparing(SystemConfigureForeheadResult::getSort))
                .collect(Collectors.toList());
        // 排序
       // systemConfigureForeheadResults.sort(Comparator.comparing(SystemConfigureForeheadResult::getSort));
        RedisTools.valueOperations().set(RedisKey.SYSTEM.CONFIGURE_POSITION_CODE +code,collect);
        log.debug("=======根据位置code刷新redis 配置信息成功=======");
    }

    /**
     * 刷新全部 xxljob
     */
     public String initAll(){
         log.debug("=======全量刷新redis 配置信息开始=======");
         Date now = new Date();
         // 查询所有有效的的配置
         List<SystemConfigure> all = systemConfigureBusiness.query(SystemConfigureQueryParam.builder()
                 .startTime(now)
                 .endTime(now)
                 .configStatus(true)
                 .build());
         if(CollectionUtils.isEmpty(all)){
             //删除所有的配置 key
             Set<String> keys = RedisTools.template().keys(RedisKey.SYSTEM.CONFIGURE_POSITION_CODE + "*");
             RedisTools.template().delete(keys);
         }
         //转换结果集
         List<SystemConfigureForeheadResult> systemConfigureForeheadResults = TransformUtils.transformList(all, SystemConfigureForeheadResult.class);

         // 初始化配置内容
         Map<String, List<SystemConfigureForeheadResult>> maps=systemConfigureForeheadResults.stream().map(this::apply)
                 .sorted(Comparator.comparing(SystemConfigureForeheadResult::getSort))
                 .collect(Collectors.groupingBy(SystemConfigureForeheadResult::getPositionCode, Collectors.toList()));
//         //处理结果集 按照位置id分组
//         Map<Long, List<SystemConfigureForeheadResult>> maps = systemConfigureForeheadResults.stream()
//                 .collect(Collectors.groupingBy(SystemConfigureForeheadResult::getPositionId, Collectors.toList()));
         List<SystemConfigureRedisForeheadResult> resultList = new ArrayList<>();
         maps.forEach((key,value)->{
             value.sort(Comparator.comparing(SystemConfigureForeheadResult::getSort));
             resultList.add(SystemConfigureRedisForeheadResult.builder().positionCode(key).results(value).build());
         });
         //刷新redis
         resultList.stream().forEach(result->
                 RedisTools.valueOperations().set(RedisKey.SYSTEM.CONFIGURE_POSITION_CODE +result.getPositionCode(),result.getResults())
         );
         log.debug("=======全量刷新redis 配置信息成功=======");
         return "success";
     }






    public static void main(String[] args) {
       String ids = "1,2";
        List<Long> shopIds = new ArrayList<>();
        Arrays.stream(ids.split(",")).forEach(
                id->shopIds.add(Long.parseLong(id))
        );
        shopIds.stream().forEach(System.out::println);
    }


    private SystemConfigureForeheadResult apply(SystemConfigureForeheadResult v) {
        log.debug(" =====配置信息==== {}"+v);
        String configContent;
        JSONObject jsonObject = new JSONObject();
        String sellerId;
        switch (ConfigType.getConfigType(v.getConfigType())) {
            case Seller:
                // 1
                configContent = v.getConfigContent();
                jsonObject = JSON.parseObject(configContent);
                sellerId = jsonObject.getString("sellerId");
                log.debug("店铺信息=== {}" + Optional.ofNullable(iShopHandler.findShopModelById(Long.parseLong(sellerId)).getData()).toString());
                v.setConfigContent(JSON.toJSONString(iShopHandler.findShopModelById(Long.parseLong(sellerId)).getData()));
                // 查询 展示图片
                // 评分 月售 起送价
                break;
            case Shop:
                configContent = v.getConfigContent();
                jsonObject = JSON.parseObject(configContent);
                List<Long> shopIds = new ArrayList<>();
                Arrays.stream(jsonObject.getString("shopIds").split(",")).forEach(
                        id -> shopIds.add(Long.parseLong(id))
                );
                log.debug("商品信息==={}" + Optional.ofNullable(iGoodsHandler.findGoodsByIds(shopIds).getData()).toString() + "商品id" + Optional.ofNullable(shopIds).toString());
                v.setConfigContent(
                        JSON.toJSONString(iGoodsHandler.findGoodsByIds(shopIds).getData()));
                // 封装 配置实体
                // [1,2,3]
                // 价格 图片
                break;
            case Picture_Seller:
                configContent = v.getConfigContent();
                jsonObject = JSON.parseObject(configContent);
                sellerId = jsonObject.getString("sellerId");
                log.debug("推荐店铺信息=== {}" + Optional.ofNullable(iShopHandler.findShopAndRecommendGoodsById(Long.parseLong(sellerId)).getData()).toString());
                v.setConfigContent(JSON.toJSONString(iShopHandler.findShopAndRecommendGoodsById(Long.parseLong(sellerId)).getData()));
                break;
        }
        return v;
    }
}
